<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card 卡片区 -->
    <el-card>
      <el-alert
        class="mr-bottom"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      ></el-alert>
      <!-- 选择商品分类 -->
      <el-row>
        <el-col>
          <span>选择商品分类:</span>
          <!-- 分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="selectedChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮添加动态参数 -->
          <el-button
            class="mr-bottom"
            @click="addDialogVisible = true"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 输入的文本框 添加tag标签的 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性表格 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 按钮添加属性 -->
          <el-button
            @click="addDialogVisible = true"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            class="mr-bottom"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
             <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(tag, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <!-- 输入的文本框 添加tag标签的 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加静态参数动态属性 对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品列表
      cateList: [],
      // 级联选择框配置
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 选择后的数据用来存放选择的数据
      selectedCateKeys: [],
      // 被激活的标签页 用来判断哪个标签页
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 添加对话框显示否 默认false
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 控制修改对话框的显示
      editDialogVisible: false,
      // 修改的表单参数对象
      editForm: {},
      // 修改表示单参数规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 获取所有商品分类
    this.getCateList()
  },
  methods: {
    // 初始化获取数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
    },
    // 请求回参数列表数据
    async getParamsData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // console.log(this.selectedCateKeys)
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 在每行添加文本框输入的值
        item.inputValue = ''
        // 在每行添加一个布尔值控制标签和输入框显示和隐藏
        item.inputVisible = false
      })
      // console.log(res)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 选择改变触发
    selectedChange() {
      // 请求回参数数据 刷新表格数据列表
      this.getParamsData()
    },
    // tab标签页点击事件
    handleTabClick() {
      // console.log(this.activeName)
      // 请求回参数数据 刷新列表
      this.getParamsData()
    },
    // 关闭对话框触发的事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 确认按钮添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('获取数据失败')
        }
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        // 请求回参数数据 刷新列表
        this.getParamsData()
      })
    },
    // 点击修改按钮展开修改对话框
    async showEditDialog(attrId) {
      this.editDialogVisible = true
      // console.log(attrId)
      //  根据 ID 查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败')
      }
      // 把请求的参数存给编辑（修改）表单的数据对象 发送修改请求的时候会用到
      this.editForm = res.data
      // console.log(this.editForm)
    },
    // 重置修改的表单
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确认修改信息
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return false
        }
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新失败')
        }
        this.$message.success('编辑成功')
        // 请求回参数数据 刷新表格数据列表
        this.getParamsData()
        this.editDialogVisible = false
        // console.log(res)
      })
    },
    // 删除一条表格数据
    async removeParams(attrId) {
      const isConfirm = await this.$confirm(
        '此操作将永久删除该条数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      // console.log(isConfirm)
      if (isConfirm !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除数据失败')
      }
      this.$message.success('删除成功')
      // 请求回参数数据 刷新表格数据列表
      this.getParamsData()
    },
    // 触发标签输入框的事件
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获取焦点
      // $nextTick 非常重要 这个表示等页面中元素都加完成后调用input.focus方法
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入完毕后把收入框变回button按钮
    async handleInputConfirm(row) {
      // 如果输入的内容为空 就重新设置为空
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = ''
        // 隐藏输入框 显示按钮
        row.inputVisible = false
        return
      }
      // console.log(row.attr_vals)
      // 如果用户输入不为空 做后序处理
      row.attr_vals.push(row.inputValue.trim())
      // row.attr_vals.pop()
      row.inputValue = ''
      // 隐藏输入框 显示按钮
      row.inputVisible = false
      // 对attr_vals对象的操作保存到数据库
      this.saveAttrVals(row)
      // console.log('--------', row.attr_vals[row.attr_vals.length - 1])
    },
    // 标签页关闭后触发
    handleClose(index, row) {
      // console.log(index)
      row.attr_vals.splice(index, 1)
      // 对attr_vals对象的操作保存到数据库
      this.saveAttrVals(row)
    },
    // 对attr_vals对象的操作保存到数据库
    async saveAttrVals(row) {
      // 发送网络请求保存到服务器
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          // attr_name: row.attr_vals[row.attr_vals.length - 1],
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('修改参数成功')
    }
  },
  computed: {
    // 按钮是否禁用
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 分类id 当前选中的3级id 发送网络请求用到
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 动态标题弹出框的
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style>
.input-new-tag {
  width: 130px !important;
}
</style>
